package com.wf.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.wf.domain.MessageInfo;
import com.wf.dto.Apart_houses;
import com.wf.dto.ContractMap;
import com.wf.dto.TaskDTO;
import com.wf.vo.Result;
import com.wf.vo.TaskRepresentationVO;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.*;

@Service
@Slf4j
public class ApprovalService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    MessageInfoService messageInfoService;
    @Autowired
    ContractInfoService contractInfoService;
    @DSTransactional
    @DS("flowable")
    public boolean startProcess(ContractMap map) {
        System.out.println("============================");
        Map<String, Object> adaptedMap = new HashMap<>();
        // 遍历原始的 map，移除 key 中的 ${}
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey().replace("${", "").replace("}", "");
            Object value = entry.getValue();
            if ("monthlyRent".equals(key) && value instanceof String) {
                value = Integer.parseInt((String) value)*1;
            }
            adaptedMap.put(key, value);
        }
        String upload = contractInfoService.upload(map);
        int j = upload.lastIndexOf("/");
        int i = upload.lastIndexOf(".");
        String contractNumber = upload.substring(j+1, i);
        System.out.println("contractNumber = " + contractNumber);
        adaptedMap.put("contractNumber",contractNumber);
        adaptedMap.put("pdf",upload);
        System.out.println(adaptedMap.get("monthlyRent"));
        ProcessInstance agency = runtimeService.startProcessInstanceByKey("ContractApproval", adaptedMap);
        System.out.println("agency = " + agency);
        Task task = taskService.createTaskQuery()
                .processInstanceId(agency.getId())
                .singleResult();
        System.out.println("111111111111111111111111111111111111");
        System.out.println("task = " + task);
        if (task!=null){
            taskService.setAssignee(task.getId(), "manager");
            return true;
        }else {
            System.out.println("task为空");
            return false;
        }
    }

    @DSTransactional
    @DS("flowable")
    public List<TaskRepresentationVO> getTasks(String assignee) {
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(assignee).list();
        List<TaskRepresentationVO> taskRepresentations = new ArrayList<>();
        for (Task task : tasks) {
            System.out.println("===========================");
            System.out.println("task = " + task);
            TaskRepresentationVO taskRepresentation = new TaskRepresentationVO();
            taskRepresentation.setTaskId(task.getId());
            taskRepresentation.setTaskName(task.getName());
            taskRepresentation.setVariables(taskService.getVariables(task.getId()));
            taskRepresentations.add(taskRepresentation);
        }
        return taskRepresentations;
    }


    @DSTransactional
    @DS("flowable")
    public Result completeTask(TaskDTO taskDTO) {
        Boolean approval = taskDTO.getApproval();
        HashMap<String, Object> map = new HashMap<>();
        map.put("approved",approval);
        Map<String, Object> variables = taskService.getVariables(taskDTO.getTaskId());
        if (approval){
            boolean b = contractInfoService.addContractInfo(variables);
            System.out.println(b?"添加成功":"添加失败");
        }else {

        }
        taskService.complete(taskDTO.getTaskId(), map);
        return Result.success(true);
    }
    @DS("flowable")
    public  List<HistoricActivityInstance>  getHistory(String assignee) {

        List<HistoricActivityInstance> instanceList = historyService.createHistoricActivityInstanceQuery()
                .taskAssignee(assignee)
                .finished()
                .list();

        return instanceList;

    }
}